<?php
declare (strict_types=1);

namespace app\listener;

use app\common\model\Trade;
use app\common\service\GatewayClientServer;
use app\index\service\TradableInterface;

class PaySuccess
{
    /**
     * 支付成功 事件监听处理
     * @param Trade $trade
     * @return void
     */
    public function handle(Trade $trade)
    {

        // 支付已成功，完成后续业务逻辑
        $tradeService = $this->getTradeService($trade->tradeTypeClass);
        if (is_null($tradeService)) {
            // TODO 记录错误日志
            return;
        }
        $tradeService->completionTrade($trade);

        // 订单支付后，更新红点
        $data = [
            'action' => REDDOT,
            'data' => [],
        ];
        $this->getGatewayClientServer()->sendToUid($trade->memberId, json_encode($data));
    }

    /**
     * 获取对应业务逻辑Service
     * @param $tradeTypeClass
     * @return TradableInterface|null
     */
    private function getTradeService($tradeTypeClass): ?TradableInterface
    {
        return app_instance(TradableInterface::class, $tradeTypeClass);
    }

    private function getGatewayClientServer(): GatewayClientServer
    {
        return app(GatewayClientServer::class);
    }
}
